Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: [#449] Implement HTTP response stream #92

Merged
merged 10 commits into from
Aug 10, 2024
Merged

Conversation

kkumar-gcc
Copy link
Member

@kkumar-gcc kkumar-gcc commented Jul 31, 2024

πŸ“‘ Description

Closes goravel/goravel#449

@coderabbitai summary

βœ… Checks

  • Added test cases for my code

@kkumar-gcc kkumar-gcc requested a review from a team as a code owner July 31, 2024 14:35
Copy link

coderabbitai bot commented Jul 31, 2024

Important

Review skipped

Auto reviews are limited to specific labels.

Labels to auto review (1)
  • πŸš€ Review Ready

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

context_response_test.go Outdated Show resolved Hide resolved
context_response_test.go Outdated Show resolved Hide resolved
context_response_test.go Outdated Show resolved Hide resolved
Comment on lines 775 to 779
scanner := bufio.NewScanner(resp.Body)
var output []string
for scanner.Scan() {
output = append(output, scanner.Text())
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I doubt that this way can't test the stream accurately. I asked GPT, could you try the code below?

package main

import (
    "time"

    "github.com/gofiber/fiber/v2"
)

func streamData(c *fiber.Ctx) error {
    c.Set(fiber.HeaderContentType, fiber.MIMETextHTMLCharsetUTF8)

    streamErr := c.Context().SetBodyStreamWriter(func(w *fiber.StreamWriter) error {
        for i := 0; i < 10; i++ {
            _, err := w.Write([]byte("Streaming data " + string(i+48) + "..."))
            if err != nil {
                return err
            }
            time.Sleep(100 * time.Millisecond) // Simulate delay between chunks
        }
        return nil
    })

    if streamErr != nil {
        return streamErr
    }

    return nil
}

func main() {
    app := fiber.New()

    app.Get("/stream", streamData)

    app.Listen(":3000")
}
package main

import (
    "bufio"
    "net/http/httptest"
    "strings"
    "testing"
    "time"

    "github.com/gofiber/fiber/v2"
    "github.com/stretchr/testify/assert"
)

func TestStreamData(t *testing.T) {
    app := fiber.New()

    app.Get("/stream", streamData)

    req := httptest.NewRequest("GET", "/stream", nil)
    resp, err := app.Test(req, -1) // -1 means read until we get the full response or the connection is closed

    assert.NoError(t, err)
    assert.Equal(t, 200, resp.StatusCode)
    assert.Equal(t, resp.Header.Get("Content-Type"), fiber.MIMETextHTMLCharsetUTF8)

    expectedChunks := []string{
        "Streaming data 0...",
        "Streaming data 1...",
        "Streaming data 2...",
        "Streaming data 3...",
        "Streaming data 4...",
        "Streaming data 5...",
        "Streaming data 6...",
        "Streaming data 7...",
        "Streaming data 8...",
        "Streaming data 9...",
    }

    reader := bufio.NewReader(resp.Body)
    for i, expected := range expectedChunks {
        chunk, err := reader.ReadString(' ')
        if err != nil {
            t.Fatalf("Failed to read chunk: %v", err)
        }
        chunk += ".." // Append rest of the string
        rest, _ := reader.ReadString('.')
        chunk += rest

        assert.Equal(t, expected, strings.TrimSuffix(chunk, "\n"), "Mismatch in chunk %d", i+1)
        // To simulate reading it with an interval as in real-time
        time.Sleep(100 * time.Millisecond)
    }
}

Copy link
Member Author

@kkumar-gcc kkumar-gcc Aug 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both are similar, current test is also doing same thing.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tested them, and yes, both of them get the final response(a,b,c), then scan the result, this way can't test the output data verbatim. It's not the perfect solution, but I think it's good enough for us now. Great job.

hwbrzzl
hwbrzzl previously approved these changes Aug 8, 2024
coderabbitai[bot]
coderabbitai bot previously approved these changes Aug 8, 2024
@kkumar-gcc kkumar-gcc dismissed stale reviews from coderabbitai[bot] and hwbrzzl via f1cf120 August 8, 2024 15:40
@kkumar-gcc kkumar-gcc requested a review from hwbrzzl August 8, 2024 16:07
ConfigFacade = mockConfig
}

t.Run("Stream", func(t *testing.T) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, we don't need this line and beforeEach in this case anymore, you can write the single test case directly.

@kkumar-gcc kkumar-gcc enabled auto-merge (squash) August 9, 2024 16:03
Copy link
Contributor

@hwbrzzl hwbrzzl left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great PR πŸ‘

@kkumar-gcc kkumar-gcc merged commit 3605b17 into master Aug 10, 2024
7 checks passed
@kkumar-gcc kkumar-gcc deleted the kkumar-gcc/#449 branch August 10, 2024 13:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

✨ [Feature] Implement HTTP response stream
2 participants